<template>
    <div>
        <MaskItem :imgPercentage="imgPercentage"></MaskItem>
        <div class="container" v-show="!showType">
            <el-tabs v-model="activeName"  type="card" @tab-click="handleClick">
                <el-tab-pane name="before" label="售前咨询">
                </el-tab-pane>
                <el-tab-pane name="after" label="售后咨询(常见问题)">
                </el-tab-pane>
            </el-tabs>
            <el-row justify="end">
                <el-col :span="24">
                    <el-button style="float: right;margin: 10px 0" type="primary" plain size="medium"  @click="addQuestionShow()">新增问题</el-button>
                </el-col>
            </el-row>
            <!-- 数据 -->
            <el-table :data="tableData" ref="multipleTable" @selection-change="handleSelectionChange">
                <!-- <el-table-column label="ID" prop="question_id"  width="40"> -->
                <!-- </el-table-column> -->
                <!-- sortable -->
                <el-table-column label="问题" prop="question">
                </el-table-column>
                <el-table-column label="操作" width="300">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="editQuestionShow(scope.row)">查看详情</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination">
                <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next, jumper" :total="total" :page-size="10">
                </el-pagination>
            </div>
        </div>
        <div v-show="showType">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                <el-breadcrumb separator="/">
                    <el-breadcrumb-item>
                        <i class="el-icon-tickets"></i> 常见问题</el-breadcrumb-item>
                </el-breadcrumb>
                <el-row justify="end">
                    <el-col :span="24">
                        <el-button style="float: right;margin: 10px 0" type="primary" plain size="medium" @click="addQuestion('ruleForm')">{{edit ? '编辑发布' : '保存发布' }}</el-button>
                        <el-button style="float: right;margin: 10px" size="medium" @click="edit = false; showType = false;">返回</el-button>
                    </el-col>
                </el-row>
                <div class="container">
                    <div class="mb-10">
                        <div class="meun-title">常见问题：</div>
                        <el-form-item label="常见问题" prop="question">
                            <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="请输入常见问题" v-model="ruleForm.question">
                            </el-input>
                        </el-form-item>
                    </div>
                    <div class="mb-10">
                        <el-form-item label="答" prop="answer">
                            <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="请输入常见问题的答案" v-model="ruleForm.answer">
                            </el-input>
                        </el-form-item>
                    </div>
                </div>
            </el-form>

            <div class="container" style="margin: 15px 0">
                <div class="meun-title">图片上传：</div>
                <div class="crop-demo-btn">点击上传
                    <input class="crop-input" type="file" name="image" accept="image/jpg, image/jpeg, image/png, image/gif" @change="uploadTypeImg($event)"/>
                </div>
                <div style="margin-top: 20px;">
                    <el-row>
                        <el-col :span="8" v-for="(o, index) in ruleForm.imgs" :key="o" :offset="index > 0 ? 2 : 0">
                            <el-card :body-style="{ padding: '0px' }">
                                <div class="image" :style="{'background-image' : 'url('+o+')'}">
                                </div>
                                <div style="padding: 14px;">
                                    <div class="bottom clearfix" style="text-align: right">
                                        <el-button type="danger" icon="el-icon-delete" circle @click="delImg(index)"></el-button>
                                    </div>
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
    import {baiduCloud} from '@/config/env'
    import {obtainQuestionsList ,appendQuestions ,delQuestions , editQuestions} from '@/config/api'
    import Mask from '../../common/mask.vue'
    import { upLoadFileToOSS } from '@/config/utils'
    export default {
        components: {
            MaskItem: Mask
        },
        data() {
            return { // 百度云
                akBos: baiduCloud.akBos,
                skBos: baiduCloud.skBos,
                endpointBos: baiduCloud.endpointBos,
                bucketImgBos: baiduCloud.bucketBos +'/course/image',
                urlImgBos: baiduCloud.urlBos+'/course/image/',
                // 图片上传进度
                imgPercentage: 0,

                // 是否編輯狀態
                edit: false,
                // 显示
                showType: false,
                url: "./static/vuetable.json",
                tableData: [],
                cur_page: 1,
                multipleSelection: [],
                ruleForm: {
                    questions_id: null,
                    // 常见问题 题目
                    question: '',
                    // 答案
                    answer: '',
                    // 图片
                    imgs: []
                },
                rules: {
                    question: [
                        { required: true, message: '请输入常见问题', trigger: 'blur' },
                    ],
                    answer: [
                        { required: true, message: '请输入答案', trigger: 'blur' },
                    ],
                },
                // 总页数
                total: 0,
                activeName: 'before',
                // 1售前 2售后
                tabsType: 1
            };
        },

        computed: {
            data() {
                return [{ index: 0 }];
            }
        },
        mounted() {
            // 百度云初始化
            this.initBaiDuBce();
            // 获取页面数据
            this.getData();

        },
        methods: {
            // tabs 切换
            handleClick(tab, event) {
                if (tab.name === 'before') {
                    this.tabsType = 1;
                } else {
                    this.tabsType = 2;
                };
                this.cur_page = 1;
                this.tableData = [];
                this.total = 0;
                this.getData();
            },
            // 获取 easy-mock 的模拟数据
            async getData() {
                let data = await obtainQuestionsList(this.cur_page,this.tabsType);
                if (data.status == 200) {
                    // 设置默认index
                    for (let i = 1 ; i < data.data.list.length; i++) {
                        this.$set( data.data.list[i],'index',i*this.cur_page)
                    };
                    if (!data.data.list.length) {
                        this.$message.error('暂无数据');
                    }
                    // 列表
                    this.tableData =  data.data.list
                    // 总数量
                    this.total =  data.data.total;

                } else  {
                    this.$message.error('暂无数据');
                }
            },
            // 新增问题
            addQuestionShow () {
                this.edit = false;
                this.showType = true;
                this.ruleForm = {
                    questions_id: null,
                        // 常见问题 题目
                        question: '',
                        // 答案
                        answer: '',
                        // 图片
                        imgs: []
                }
            },
            // 新增问题
            async addQuestion (formName) {
                  this.$refs[formName].validate((valid) => {
                      if (valid) {
                          if (!this.edit) {
                              appendQuestions(this.ruleForm,this.tabsType)
                                  .then( res => {
                                      console.log('添加数据',res)
                                      if (res.status === 200) {
                                          this.edit = false;
                                          this.showType = false;
                                          // 获取页面数据
                                          this.getData();
                                          this.$message({
                                              message: '添加成功',
                                              type: 'success'
                                          });
                                      } else {
                                          this.$message.error('失败');
                                      }
                                  }).catch( err => {
                                  console.error(err)
                              })
                          } else {
                              editQuestions(this.ruleForm)
                                  .then( res => {
                                      console.log('修改数据',res)
                                      if (res.msg === 'success') {
                                          this.edit = false;
                                          this.showType = false;
                                          // 获取页面数据
                                          this.getData();
                                      } else {
                                          this.$message.error('失败');
                                      }
                                  }).catch( err => {
                                  console.error(err)
                              })
                          }

                      } else {
                          console.log('error submit!!');
                          return false;
                      }
                  });
            },
            // 删除问题
            async handleDelete(index, row) {
                console.log(index, row);
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delQuestions(row.question_id)
                        .then(res => {
                            console.log(res,'删除成功')
                            if (res.msg === 'success') {
                                // 获取页面数据
                                this.getData();
                                this.$message({
                                    message: '删除成功！',
                                    type: 'success'
                                });
                            } else {
                                this.$message.error('失败');
                            }
                        }).catch ( err => {
                        console.log(err)
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            // 编辑问题
            async editQuestionShow(row) {
                this.edit = true;
                this.showType = true;
                this.ruleForm = row;
            },

            // 删除图片
            async delImg (index) {
                this.ruleForm.imgs.splice(index,1);
            },
            // 初始化百度云上传
            initBaiDuBce(){
                let self = this;
                let bosConfig = {
                    credentials: {
                        ak: self.akBos,
                        sk: self.skBos
                    },
                    endpoint: self.endpointBos  // 根据您选用bos服务的区域配置相应的endpoint
                };
                // let bucket = self.bucketBos; // 设置您想要操作的bucket
                self.client = new baidubce.sdk.BosClient(bosConfig);
            },
            // 上传图片
            async uploadTypeImg(event, status){
                let self = this;
                // 课程类型图片状态    0 --- 课程类型banner  1 --- 课程类型证书  2 --- 课程类型介绍
                self.uploadStatus = status;

                // 浏览器兼容 (FF不兼容event.srcElement)
                let evt = event.srcElement ? event.srcElement : event.target;
                let file = evt.files[0]; // 获取要上传的文件
                // 用户取消上传
                if(file == undefined){
                    return;
                }

                
                const url = await upLoadFileToOSS(file, 'course/image')
                if (url) {
                    self.ruleForm.imgs=[url]
                }
                return false;
                // 生成6位随机数
                let chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
                let res = "";
                for(let i = 0; i < 6 ; i ++) {
                    let id = Math.ceil(Math.random()*61);
                    res += chars[id];
                }
                let key = res +'_'+new Date().getTime()+ '.' +file.name.split(/\./g).pop(); // 保存到bos时的key，您可更改，默认以文件名作为key
                let blob = file;
                let ext = key.split(/\./g).pop();
                let mimeType = baidubce.sdk.MimeType.guess(ext);
                if (/^text\//.test(mimeType)) {
                    mimeType += '; charset=UTF-8';
                }
                let options = {
                    'Content-Type': mimeType
                };
                self.client.putObjectFromBlob(self.bucketImgBos, key, blob, options)
                    .then(function (res) {
                        // 上传完成，添加您的代码
//                        console.log(key,res,'上传成功');
//                        // banner
//                        if (self.uploadStatus === 1  ) {
//                            self.bannerImg = self.urlImgBos + key;
//                        };
//                        // 课程介绍图
//                        if (self.uploadStatus === 2 ) {
//                            self.courseImg = self.urlImgBos + key;
//                        };
                        self.ruleForm.imgs=[self.urlImgBos + key]
                        console.log('图片上传成功:',self.urlImgBos + key)
                    })
                    .catch(function (err) {
                        // 上传失败，添加您的代码
                        console.log(err);
                    });

                self.client.on('progress', function (evt){
                    // console.log(evt, ".....")
                    // 监听上传进度
                    if (evt.lengthComputable){
                        self.imgPercentage = parseInt((evt.loaded / evt.total) * 100)+'';
                        console.log(self.imgPercentage, "上传图片")
                        self.imgPercentage = String(self.imgPercentage)
                        // 满了，清空进度条
                        if(self.imgPercentage == 100){
                            self.imgPercentage = 0
                        }
                    }
                });
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 分页导航
            handleCurrentChange(val) {
                this.cur_page = val;
                this.getData();
            }
        }
    };
</script>

<style lang="less" scoped>
    .crop-demo-btn{
        position: relative;
        width: 150px;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        background-color: #409eff;
        color: #fff;
        font-size: 14px;
        border-radius: 4px;
        box-sizing: border-box;
        text-align: center;
    }
    .crop-input{
        position: absolute;
        width: 150px;
        height: 40px;
        left: 0;
        top: 0;
        opacity: 0;
        cursor: pointer;
    }
    .mb-10 {
        margin-bottom: 10px;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .question-avatar-upload-img {
        margin-top: 10px;
        width: 178px;
        height: 178px;
        display: block;
    }
    .meun-title {
        margin-bottom: 5px;
    }
    .image {
        width: 100%;
        height: 300px;
        background-repeat: no-repeat;
        background-position: center center;
        -webkit-background-size: cover;
        background-size: cover;
    }
</style>
